package cn.monkey.family.server.domain.shop.item.comment;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.context.Context;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.shop.item.comment.CommentDto;
import cn.monkey.family.data.shop.item.comment.CommentQueryRequest;
import cn.monkey.family.data.shop.item.comment.CommentVo;
import com.google.common.base.Strings;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("shop/item/{itemId}/comment")
public class CommentController {
    final ICommentService commentService;

    public CommentController(ICommentService commentService) {
        this.commentService = commentService;
    }

    @GetMapping({"/id", ""})
    Result<?> get(@Context RequestContext context,
                  @PathVariable(value = "itemId") String itemId,
                  @PathVariable(value = "id", required = false) String id,
                  @RequestParam(value = "action", required = false) String action,
                  @RequestParam(value = "maxDeep", required = false) Integer maxDeep,
                  CommentQueryRequest queryRequest,
                  @PageableDefault Pageable pageable) {
        queryRequest = queryRequest.toBuilder().itemId(itemId).build();
        if (!Strings.isNullOrEmpty(id)) {
            return this.commentService.readById(context, id);
        }
        if ("tree".equals(action)) {
            return this.commentService.readTree(context, queryRequest, pageable.getSort(), maxDeep);
        }
        if ("getRoot".equals(action)) {
            return this.commentService.readRoot(context, queryRequest, pageable.getSort());
        }
        return this.commentService.readPage(context, queryRequest, pageable);
    }

    @PostMapping
    Result<CommentVo> create(@Context RequestContext context,
                             @PathVariable(value = "itemId") String itemId,
                             @RequestBody CommentDto commentDto) {
        commentDto.setItemId(itemId);
        return this.commentService.create(context, commentDto);
    }

    @DeleteMapping
    Result<Void> delete(@Context RequestContext context,
                        @RequestBody String id) {
        return this.commentService.delete(context, id);
    }
}
